<template>
  <div class="map-wrapper">
    <div id="map"></div>
    <div class="actions">
      <button @click="controlLayer('dike')">堤防</button>
      <button @click="controlLayer('wgate')">水闸</button>
      <button @click="controlLayer('pump')">泵站</button>
      <!-- <button @click="controlLayer('weik')">圩口</button> -->
      <button @click="controlLayer('reservoir')">水库</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Map from 'ol/Map'
import View from 'ol/View'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Fill, Stroke, Circle, Style, Text, Icon } from 'ol/style'
import { GeoJSON } from 'ol/format'
import { defaults } from 'ol/control'
import Feature from 'ol/Feature'
import { Point, LineString, Polygon } from 'ol/geom'
import dikeData from './apiData/wpoDike.json'
import gateData from './apiData/wpoGate.json'
import weikouData from './apiData/weikou.json'
import wpoResBaseData from './apiData/wpoResBase.json'
import wpoPumpStationData from './apiData/wpoPumpStation.json'

export default {
  components: {},
  props: {},
  data() {
    return {
      map: null
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.initMap()
    this.createMap()

    this.addDikeLayer()

    this.addGateLayer()

    // this.addWkLayer()

    this.addReservoir()

    this.addPumpStation()
  },
  activated() {},
  deactivated() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    initMap() {
      this.map = new Map({
        target: 'map',
        layers: [],
        view: new View({
          projection: 'EPSG:4326',
          center: [116.502429, 30.530761],
          zoom: 8.5 // 默认缩放级别
        }),
        // 设置地图控件，默认的三个控件都不显示
        controls: defaults({
          attribution: false,
          rotate: false,
          zoom: false
        })
      })
    },
    async createMap() {
      const res = await axios.get('/aq-geojson/340800_full.json')
      const data = res.data
      const layer = new VectorLayer({
        source: new VectorSource({
          features: new GeoJSON().readFeatures(data, {
            featureProjection: 'EPSG:4326'
          })
        }),
        style: function (feature) {
          const name =
            feature.get('name') ||
            feature.get('NAME') ||
            feature.get('名称') ||
            ''
          return new Style({
            fill: new Fill({
              // color: 'rgba(64, 158, 255, 0.8)'
              color: '#000'
            }),
            stroke: new Stroke({
              color: '#fff',
              width: 2
            }),
            text: new Text({
              text: name,
              font: '12px sans-serif',
              fill: new Fill({
                color: '#fff'
              }),
              stroke: new Stroke({
                color: '#000',
                width: 3
              })
            })
          })
        }
      })
      this.map.addLayer(layer)
    },
    //堤防
    addDikeLayer() {
      let geojson = {
        name: '堤防',
        type: 'FeatureCollection',
        features: []
      }

      dikeData.forEach(el => {
        if (el.geoJson && Object.keys(el.geoJson).length) {
          el.geoJson.properties.typeLabel = el.typeLabel
          el.geoJson.properties.typeValue = el.typeValue
          return geojson.features.push(el.geoJson)
        }
      })

      let sourceGeojson = new VectorSource({
        wrapX: false,
        features: new GeoJSON().readFeatures(geojson)
      })
      const layer = new VectorLayer({
        source: sourceGeojson,
        style: function (feature, resolution) {
          return new Style({
            stroke: new Stroke({
              color: '#e38134',
              width: 3
            }),
            text: new Text({
              text: feature.get('value'),
              font: 'bold 12px sans-serif',
              fill: new Fill({
                color: 'rgba(255, 255, 255)'
              })
            })
          })
          /* if (resolution < 0.0005) {
          } else {
            return null
          } */
        },
        zIndex: 5
      })
      layer.set('name', 'dike')

      this.map.addLayer(layer)
    },
    //水闸
    addGateLayer() {
      const list = gateData
      let features = []
      for (let item of list) {
        if (item.longitude && item.latitude) {
          let fea = new Feature({
            geometry: new Point([item.longitude, item.latitude]),
            iconFlag: 'waterGate'
          })
          fea.setProperties(item)
          features.push(fea)
        }
      }
      const layer = new VectorLayer({
        source: new VectorSource({
          features: features
        }),
        style: function (feature, resolution) {
          return new Style({
            image: new Icon({
              anchor: [0.5, 0.5],
              //offset:[0,20],
              scale: 0.5,
              opacity: 1,
              src: '/img/comprehensive-display/map-point-icon/water-gate.png'
            })
            /* text: new Text({
              text: feature.get('name'),
              font: 'bold 12px sans-serif',
              fill: new Fill({
                color: 'rgba(255, 255, 255)'
              }),
              offsetX: 0,
              offsetY: 20
            }) */
          })
          /* if (resolution < 0.0005) {
          } else {
            return null
          } */
        },
        zIndex: 6
      })
      layer.set('name', 'wgate')

      this.map.addLayer(layer)
    },
    // 泵站
    addPumpStation() {
      const list = wpoPumpStationData
      let features = []
      for (let item of list) {
        if (item.longitude && item.latitude) {
          let fea = new Feature({
            geometry: new Point([item.longitude, item.latitude]),
            iconFlag: 'pumpStation'
          })
          fea.setProperties(item)
          features.push(fea)
        }
      }
      const layer = new VectorLayer({
        source: new VectorSource({
          features: features
        }),
        style: function (feature, resolution) {
          return new Style({
            image: new Icon({
              anchor: [0.5, 0.5],
              //offset:[0,20],
              scale: 0.5,
              opacity: 1,
              src: '/img/comprehensive-display/map-point-icon/pump-station.png'
            })
            /* text: new Text({
                text: feature.get('name'),
                font: 'bold 12px sans-serif',
                fill: new Fill({
                  color: 'rgba(255, 255, 255)'
                }),
                offsetX: 0,
                offsetY: 20
              }) */
          })
          // if (resolution < 0.0005) {
          // } else {
          //   return null
          // }
        },
        zIndex: 7
      })
      layer.set('name', 'pump')
      this.map.addLayer(layer)
    },
    //圩口
    addWkLayer() {
      let feas = new GeoJSON().readFeatures(weikouData)
      feas.forEach(feature => {
        feature.set('wkflag', 'weikou')
      })
      let weikLayer = new VectorLayer({
        source: new VectorSource({
          features: feas
        }),
        style: function (feature, resolution) {
          let name = feature.get('name') ? feature.get('name') : ''
          let normalStyle = new Style({
            stroke: new Stroke({
              // color: 'rgb(112,176,88)',
              // width: 0.2
              color: 'rgba(255,255,255, 0.5)',
              width: 2,
              lineDash: [5, 5]
            }),
            fill: new Fill({
              // color: 'rgba(0,255,235, 0.5)'
              color: 'red'
            }),
            text: new Text({
              offsetY: 20,
              text: resolution < 0.0006 ? name : '',
              font: '12px Calibri,sans-serif',
              fill: new Fill({
                color: '#fff'
              })
            })
          })
          return normalStyle
        },
        zIndex: 8
        // opacity: 0.7
      })
      weikLayer.set('name', 'weik')
      this.map.addLayer(weikLayer)
    },
    //水库
    addReservoir() {
      let geojson = {
        name: '水库',
        type: 'FeatureCollection',
        features: []
      }
      wpoResBaseData.forEach(el => {
        if (el.geoJson && Object.keys(el.geoJson).length) {
          el.geoJson.properties.typeLabel = el.typeLabel
          el.geoJson.properties.typeValue = el.typeValue
          el.geoJson.properties.iconFlag = 'skicon'
          return geojson.features.push(el.geoJson)
        }
      })
      let sourceGeojson = new VectorSource({
        wrapX: false,
        features: new GeoJSON().readFeatures(geojson)
      })
      const layer = new VectorLayer({
        source: sourceGeojson,
        style: function (feature, resolution) {
          return new Style({
            fill: new Fill({
              color: 'rgba(40,120,255,0.5)'
            })
          })
        },
        zIndex: 9
      })
      layer.set('name', 'reservoir')
      this.map.addLayer(layer)
    },
    // 控制图层的显示和隐藏
    controlLayer(name) {
      let layer = this.map
        .getLayers()
        .getArray()
        .find(item => item.get('name') === name)
      if (layer) {
        layer.setVisible(!layer.getVisible())
      }
    }
  },
  filters: {}
}
</script>
<style scoped lang="scss">
.map-wrapper {
  height: 100%;
  position: relative;
  #map {
    height: 100%;
    width: 100%;
    background: url(./images/map-bg.png);
    background-size: cover;
    background-repeat: no-repeat;
  }
  .actions {
    position: absolute;
    bottom: 10px;
    left: 10px;
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      background-color: #409eff;
      color: #fff;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover {
        background-color: #66b1ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      }
    }
  }
}
</style>
